terraform {
  required_providers {
    oci = {
      source  = "oracle/oci"
      version = ">= 4.0.0"
    }
  }
}

provider "oci" {
  region = var.region
}

# Create multiple compute instances
resource "oci_core_instance" "compute_instances" {
  count               = var.instance_count
  availability_domain = var.availability_domain
  compartment_id      = var.compartment_id
  display_name        = "${var.instance_displayname}-${count.index + 1}"
  shape               = var.instance_shape
  preserve_boot_volume = false
  
  create_vnic_details {
    subnet_id        = var.subnet_id
	assign_private_dns_record = "true"
	assign_public_ip = "false"
  }

  source_details {
    source_type = "image"
    source_id   = var.instance_image_id
    boot_volume_size_in_gbs = var.root_volume_size
    boot_volume_vpus_per_gb = "10"
  }

  metadata = {
    ssh_authorized_keys = var.ssh_public_key != "" ? var.ssh_public_key : null
    user_data = base64encode(<<-EOF
              #!/bin/bash
              # Wait for the data volume to be attached
              while [ ! -e /dev/oracleoci/oraclevdb ]; do
                sleep 1
              done
              
              # Create /data directory if it doesn't exist
              mkdir -p /data
              
              # Check if the volume is already formatted
              if ! blkid /dev/oracleoci/oraclevdb; then
                # Format the volume with xfs filesystem
                mkfs.xfs /dev/oracleoci/oraclevdb
              fi

              # 获取UUID
              DEVICE_UUID=$(blkid -s UUID -o value /dev/oracleoci/oraclevdb)

              # Add entry to fstab for persistent mount
              echo "UUID=$${DEVICE_UUID} /data xfs defaults,_netdev,nofail 0 2" >> /etc/fstab
              
              # Mount the volume
              mount -a
              EOF
    )
  }

  shape_config {
    baseline_ocpu_utilization = "BASELINE_1_1"
    ocpus         = var.ocpus
    memory_in_gbs = var.memory_in_gbs
  }

  # Add launch options for better performance
  launch_options {
    boot_volume_type = "PARAVIRTUALIZED"
    network_type     = "PARAVIRTUALIZED"
  }
}

# Create data volumes for each instance
resource "oci_core_volume" "data_volumes" {
  count               = var.instance_count
  availability_domain = var.availability_domain
  compartment_id      = var.compartment_id
  display_name        = "${var.instance_displayname}-${count.index + 1}"
  size_in_gbs        = var.data_volume_size
}

# Attach data volumes to instances
resource "oci_core_volume_attachment" "data_volume_attachments" {
  count           = var.instance_count
  attachment_type = "paravirtualized"
  instance_id     = oci_core_instance.compute_instances[count.index].id
  volume_id       = oci_core_volume.data_volumes[count.index].id
  display_name    = "${var.instance_displayname}-${count.index + 1}-data"
  device          = "/dev/oracleoci/oraclevdb"
}